package com.Example;

import com.Example.Model.Transfer.Transfer;
import com.Example.Model.User;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.client.RepChainClient;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.protos.Peer;
import com.websocket.wsCallBack;
import com.websocket.Observer;
import com.websocket.wsSyncClient;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.net.URI;

import static java.lang.Thread.sleep;

public class Test implements wsCallBack, Observer {

    private String name;
    private Peer.Event message;
    String host = "192.168.2.69:8081";
    RepChainClient client = new RepChainClient(host);

    public Test(String name) {
        this.name = name;
    }

    public Test() {

    }

    // 用来测试订阅消息
    public void invoke() {
        wsSyncClient server = null;
        try {
            server = new wsSyncClient(new URI("ws://" + "192.168.2.69:8081" + "/event"));
            URI uri = server.getURI();
            String host = uri.getHost();
            Observer userZhang = new User("RepChain");
            Observer test = new Test("zyf");
            server.createObserverList();
            server.registerObserver(test);
            server.connect();
//            sleep(2000); // 确保已经连上websocket
//            while (server.isOpen()) {
//                server.notifyObserver();
//                server.feedBack(Test.this);
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 用来测试提交交易的回调方法
    public void commitTrans() {
        String str_trans = "";
        String str_supply = "";
//        String host = "192.168.2.69:8081";
//        RepChainClient client = new RepChainClient(host);
        client.setJksPath("jks/mykeystore_1.jks");
        client.setPassword("123");
        client.setAlias("1");
        try {
            str_trans =  Files.asCharSource(new File("Json/transfer_1.json"), Charsets.UTF_8).read(); // google的包,最新的Files.toString()即将废弃
            str_supply = FileUtils.readFileToString(new File("Tpl/SupplyTPL.scala"), Charsets.UTF_8);  // apache commons的包
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        }

//        Transaction t1 = Transaction.newBuilder().build();
        try {
            String chainCodeId = "3bf632f6262f9e1742b1f12c3992d91c0a2f6e9b7e7d0f65f3fb356a4f398c62";  //这个是给转账交易示范用的，此ID需要与repchain合约部署的一致
            // 构建转账交易1   chainCodeId 是部署好的合约的txid；
            Peer.Transaction transfer = client.createTransaction(Peer.Transaction.Type.CHAINCODE_INVOKE, "path",
                    "transfer" ,str_trans,"string", chainCodeId, Peer.ChaincodeSpec.CodeType.CODE_SCALA);
            byte[] bytes = transfer.toByteArray();
            String transferstr = Hex.encodeHexString(bytes);
            // 构建转账交易2
            Transfer trans = new Transfer();  // 也可以直接用构造函数进行构造 new Transfer("st","st","int")
            trans.setFrom("1MH9xedPTkWThJUgT8ZYehiGCM7bEZTVGN");
            trans.setTo("12kAzqqhuq7xYgm9YTph1b9zmCpZPyUWxf");
            trans.setAmount(5);
            Peer.Transaction transfer1 = client.createTransaction(Peer.Transaction.Type.CHAINCODE_INVOKE, "path",
                    "transfer" , JSON.toJSONString(trans),"string", chainCodeId, Peer.ChaincodeSpec.CodeType.CODE_SCALA);
            //将交易数据post过去
            client.postTranByString(Test.this, JSONObject.toJSONString(transferstr),transfer);
            System.out.println("wait");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     *
     * @param flag
     * @param result
     */
    @Override
    public void preDoTransaction(Boolean flag, JSONObject result) {
        System.out.println("*******");
        if (flag)
            System.out.println("预执行成功");
        else
            System.out.println("预执行失败");
//        System.out.println(flag);
        System.out.println("*******");
    }

    /**
     *
     * @param flag
     * @param block
     * @param result
     */
    @Override
    public void verifyBlock(Boolean flag, Peer.Block block, String result) {
        System.out.println("######");
//        System.out.println(flag);
//        System.out.println(block);
        if (flag)
            System.out.println("已经确认出块,块内的交易数量：" + block.getTransactionsList().size());
        else
            System.out.println("预执行可能错误，未入块");
        System.out.println("######");
    }


    /**
     *
     * @param message 订阅到的消息
     */
    @Override
    public void notify(Peer.Event message) {
        this.message = message;
        if (message.hasBlk()) {
            readTransNum();
        }
    }

    public void readTransNum() {
        System.out.println(name + " Block内Transactions的条数： " +  message.getBlk().getTransactionsList().size());
    }
}
